define(['zepto', 'utils', 'JST'], function($, utils, JST){
  return {
    init: function(_CTX_, temp) {
      this._CTX_ = _CTX_
      this.temp = temp
      this.modal = {}

      this.$bmiEdit = $('[href="#bmi-edit"]')

      this.$bmiEdit.length ? this.bindPushAction() : void 0
    },

    bindPushAction: function() {

      var that = this

      // on location edit
      $(document).on('click', '[href="#bmi-edit"]', function(e) {
        e.preventDefault()
        var defer = that.compileBmiPage()

        $.when(defer).done(function($page) {
                $.push.transitionIn($page)
            })

      })

      // On location edited
      this.$bmiEdit.on('edited:profile:bmi', function(e, $page, bmi, time) {

        var itemDomString = $(JST.bmiItemTpl({
          'bmi': bmi,
          'time': time
        }))

        if(that.temp) {
          $.toast("修改我BMI数据成功");
          setTimeout(function() {
                  window.location.reload()
                 }, 500)
        } else {
          $.push.transitionOut($page, {
            beforeTransition: function() {
              that.$bmiEdit.off()
                .parent().empty().html(itemDomString)
              that.$bmiEdit.parent().trigger("refresh")
            }
          })
        }
      })
    },

    compileBmiPage: function() {

      var that = this,
        deferPage = $.Deferred(),
        defer = this.requestBmi()

      $.when(defer).done(function(data) {

        that.modal.genderDisplay = data.genderDisplay
        that.modal.genderValue = data.genderValue
        that.modal.height = data.height
        that.modal.weight = data.weight

        var $page = $(JST.bmiEditTpl({
          'genderDisplay': data.genderDisplay,
          'genderValue': data.genderValue,
          'height': data.height,
          'weight': data.weight
        }))

        // Bind submit
        that.bindBmiEditPageEvent($page)

        // Set defer as resolve status
        deferPage.resolve($page)
      })

      return deferPage.promise()
    },

    requestBmi: function() {
      var defer = $.Deferred(),
              url = this._CTX_.root + '/profile/bmi'

          // Show request indicator
          $.showIndicator()

          // Request for rounds data
          $.ajax({
            'type': 'GET',
            'url': url,
            'cache': false
          }).done(function(response) {
            $.hideIndicator()  // Hide request indicator
            utils.processResult(response, function(result) {
                defer.resolve(result.data)
            }, function(result) {
                $.toast(result.message || '获取BMI数据失败')
            })
          })

        return defer.promise()
    },

    bindBmiEditPageEvent: function($page) {
      var that = this,
        $height = $('input[name="height"]', $page),
        $weight = $('input[name="weight"]', $page),
        $gender = $('input[name="gender"]', $page),
        $genderSelector = $('input[name="genderSelector"]', $page)

      $genderSelector.picker({
            toolbarTemplate: '<header class="bar bar-nav">\
                                <button class="button button-link pull-right close-picker">确定</button>\
                                <h1 class="title">请选择性别</h1>\
                             </header>',
            cols: [
              {
                  textAlign: 'center',
                values: ['MALE', 'FEMALE'],
                displayValues: ['男', '女']
              }
            ],
            formatValue: function (picker, value, displayValue){
              $(this.input).next().val(value)

              that.modal.genderDisplay = displayValue
              that.modal.genderValue = value
              
              return displayValue
            }
          });
        
        $page.on('click', '#submit', function(e) {

          e.preventDefault()

          var height = $height.val().trim()
          if(!height) $.toast('身高不能为空');

          var weight = $weight.val().trim()
          if(!weight) $.toast('体重不能为空');

          var gender = $gender.val().trim()
        if(!gender) $.toast('性别不能为空');

          var submiting = that.submitBmi(height, weight, gender)
          $.when(submiting).done(function(data) {
            that.$bmiEdit.trigger('edited:profile:bmi', [$page, '24.6', '2016-06-13'])
          })
        })
    },

    submitBmi: function(height, weight, gender) {
      var that = this, defer = $.Deferred()
      $.showIndicator()
      $.post(that._CTX_.root + "/profile/bmi", {
        'height': height,
        'weight': weight,
        'gender': gender,
        '_method': 'PATCH'
      }).done(function(response) {
        $.hideIndicator()
              utils.processResult(response, function(result) {
                defer.resolve(result.data)
            }, function(result) {
                $.toast(result.message || '修改失败')
                defer.resolve(result.data)
            })
      })
    }
  }
})